﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TestPhone.Resources;
using Microsoft.Phone.Storage;
using VBFOOL.MediaPlayer.Core;
using System.IO.IsolatedStorage;
using Windows.Phone.Storage.SharedAccess;
using System.Collections.ObjectModel;
using System.Collections;

namespace TestPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            // 用于本地化 ApplicationBar 的示例代码
            // BuildLocalizedApplicationBar();
            InitFileList();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                if (NavigationContext.QueryString.ContainsKey("fileToken"))
                {
                    var filetoken = NavigationContext.QueryString["fileToken"];
                    OpenSharedFile(filetoken);
                }

            }

            base.OnNavigatedTo(e);
        }

        async void OpenSharedFile(string Filetoken)
        {
            var fn = SharedStorageAccessManager.GetSharedFileName(Filetoken);
            var lf = Windows.Storage.ApplicationData.Current.LocalFolder;
            var fd = await lf.GetFolderAsync("Download");
            var f = await SharedStorageAccessManager.CopySharedFileAsync(fd, fn, Windows.Storage.NameCollisionOption.GenerateUniqueName, Filetoken);
            var p = "Download";
            var n = f.Name;
            var filename = System.IO.Path.Combine(p, n);
            SetLocalStream(filename);
        }

        private void SetLocalStream(string filename)
        {
            if (MyFiles.FileExists(filename))
            {
                var result = MyFiles.OpenFile(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                App.PlayingStream = result;
                this.NavigationService.Navigate(new Uri("/PlayerPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        IsolatedStorageFile MyFiles = IsolatedStorageFile.GetUserStoreForApplication();
        IList<SelectObject> FileSourceList = null;
        async void InitFileList()
        {
            if (!MyFiles.DirectoryExists("Download"))
            {
                MyFiles.CreateDirectory("Download");
            }
            FileSourceList = new System.Collections.ObjectModel.ObservableCollection<SelectObject>();
            FileSourceList.Add(new FolderObject() { Title = "本机离线", Folder = "Download" });
            var ex = await ExternalStorage.GetExternalStorageDevicesAsync();
            var sd = ex.FirstOrDefault();
            if (sd != null)
            {
                FileSourceList.Add(new ExternalFolderObject() { Title = "存储卡", Folder = sd.RootFolder });
            }
            MyList.ItemsSource = FileSourceList as IList;
        }

        async void AddExternFolders(ExternalFolderObject obj)
        {
            var backtile = new BackToMainObject() { Title = "返回上层", BackList = FileSourceList };
            var folder = obj.Folder;
            var ls = await folder.GetFoldersAsync();
            var fs = await folder.GetFilesAsync();
            var lst = ls.Select(m => new ExternalFolderObject() { Title = m.Name, Folder = m });
            var fst = fs.Select(m => new ExternalFileObject() { Title = m.Name, File = m });
            FileSourceList = new System.Collections.ObjectModel.ObservableCollection<SelectObject>();
            FileSourceList.Add(backtile);
            foreach (var item in lst)
            {
                FileSourceList.Add(item);
            }
            foreach (var item in fst)
            {
                FileSourceList.Add(item);
            }
            MyList.ItemsSource = FileSourceList as IList;
        }

        void AddFolders(FolderObject obj)
        {
            var backtile = new BackToMainObject() { Title = "返回上层", BackList = FileSourceList };
            var folder = System.IO.Path.Combine(obj.Folder, "*");
            var folder1 = System.IO.Path.Combine(obj.Folder, "*.mkv");
            var ls = MyFiles.GetDirectoryNames(folder);
            var fs = MyFiles.GetFileNames(folder1);
            var lst = ls.Select(m => new FolderObject() { Title = m, Folder = System.IO.Path.Combine(obj.Folder, m) });
            var fst = fs.Select(m => new FileObject() { Title = m, Filename = System.IO.Path.Combine(obj.Folder, m) });
            FileSourceList = new System.Collections.ObjectModel.ObservableCollection<SelectObject>();
            FileSourceList.Add(backtile);
            foreach (var item in lst)
            {
                FileSourceList.Add(item);
            }
            foreach (var item in fst)
            {
                FileSourceList.Add(item);
            }
            MyList.ItemsSource = FileSourceList as IList;
        }

        async void SetStream(ExternalStorageFile f)
        {
            var stm = await f.OpenForReadAsync();
            App.PlayingStream = new SDCardFileStream(stm);
            this.NavigationService.Navigate(new Uri("/PlayerPage.xaml", UriKind.RelativeOrAbsolute));
        }

        //BackToMainObject backtile = null;
        private void TileItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = sender as FrameworkElement;
            var obj = item.DataContext as SelectObject;
            if (obj is ExternalFolderObject)
            {
                AddExternFolders((obj as ExternalFolderObject));
            }
            else if (obj is ExternalFileObject)
            {
                SetStream((obj as ExternalFileObject).File);
            }
            else if (obj is FileObject)
            {
                var fs = obj as FileObject;
                SetLocalStream(fs.Filename);
            }
            else if (obj is FolderObject)
            {
                var fl = obj as FolderObject;
                AddFolders(fl);
            }
            else if (obj is BackToMainObject)
            {
                var b = obj as BackToMainObject;
                if (b.BackList != null)
                {
                    FileSourceList = b.BackList;
                    MyList.ItemsSource = FileSourceList as IList;
                }
                else
                {
                    InitFileList();
                }
            }
            //MyList.SelectedIndex = -1;
        }

        private void TileItem_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menu = sender as MenuItem;
            var item = menu.DataContext as FileObject;
            if (item!=null && MyFiles.FileExists(item.Filename))
            {
                MyFiles.DeleteFile(item.Filename);
                FileSourceList.Remove(item);
            }
        }




        //// 用于生成本地化 ApplicationBar 的示例代码
        //private void BuildLocalizedApplicationBar()
        //{
        //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
        //    ApplicationBar = new ApplicationBar();

        //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = "播放";//AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // 使用 AppResources 中的本地化字符串创建新菜单项。
        //    //ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    //ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}



    }
}